<?php

namespace App\Http\Controllers\Admin;
use App\Users;
use App\Record;
use App\Collection;
use App\Manage;
use App\Address;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Excel;

class UsersController extends Controller
{
    //用户列表
    protected static $field = [
        ['id'=>1,'searchtype'=>'编号'],
        ['id'=>2,'searchtype'=>'创建时间'],
        ['id'=>3,'searchtype'=>'更新时间'],
        ['id'=>4,'searchtype'=>'权重'],
        ['id'=>5,'searchtype'=>'用户名'],
        ['id'=>6,'searchtype'=>'积分'],
        ['id'=>7,'searchtype'=>'用户手机'],
        ['id'=>8,'searchtype'=>'用户邮箱'],
        ['id'=>9,'searchtype'=>'性别'],
        ['id'=>10,'searchtype'=>'出生年月'],
        ['id'=>11,'searchtype'=>'车牌号'],
        ['id'=>12,'searchtype'=>'身份证号'],
        ['id'=>13,'searchtype'=>'客户经理'],
        ['id'=>14,'searchtype'=>'批次号'],
        ['id'=>15,'searchtype'=>'用户状态'],
    ];

    //载入用户列表页
    public function index()
    {
        $search = Input::get('searchtype');
        $param = Input::get('param');
        $obj = new Users;
        if ($search == 1) {
            $obj = $obj->where('id', 'like', "%$param%");
            //dd($obj);
        } elseif ($search == 2) {
            $obj = $obj->where('create_time', 'like', "%$param%");
        } elseif ($search == 3) {
            $obj = $obj->where('update_time', 'like', "%$param%");
        } elseif ($search == 4) {
            $obj = $obj->where('rank', 'like', "%$param%");
        } elseif ($search == 5) {
            $obj = $obj->where('name', 'like', "%$param%");
        } elseif ($search == 6) {
            $obj = $obj->where('integral', 'like', "%$param%");
        } elseif ($search == 7) {
            $obj = $obj->where('phone', 'like', "%$param%");
        } elseif ($search == 8) {
            $obj = $obj->where('email', 'like', "%$param%");
        } elseif ($search == 9) {
            $obj = $obj->where('sex', 'like', "%$param%");
        } elseif ($search == 10) {
            $obj = $obj->where('birth', 'like', "%$param%");
        } elseif ($search == 11) {
            $obj = $obj->where('car_num', 'like', "%$param%");
        } elseif ($search == 12) {
            $obj = $obj->where('user_num', 'like', "%$param%");
        } elseif ($search == 13) {
            $man = Manage::where('username','like',"%$param%")->first();
            $obj = $obj->where('mid',$man['id']);
        } elseif ($search == 14) {
            $obj = $obj->where('u_batch', 'like', "%$param%");
        } elseif ($search == 15) {
            $obj = $obj->where('status', 'like', "%$param%");
        }
        $sid = Session::get('id');
        $roleid = Session::get('roleid');
        $d = array();
        $t = array();
        if ($roleid == 1) {
            $list = $obj->Paginate(10)->toArray();
        //dd($list);
            if ($list == false && !empty($search)) {
                return redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            for ($i = 0; $i < count($list['data']); $i++) {
                if ($list['data'][$i]['status'] == 1) {
                    $list['data'][$i]['status'] = "1(已启用)";
                } else {
                    $list['data'][$i]['status'] = "0(已禁用)";
                }
                $list['data'][$i]['ip'] = long2ip($list['data'][$i]['ip']);
            }
            $list['searchtype'] = self::$field;
            $man = $obj->Paginate(10);
        }
        elseif($roleid == 2) {
            $id = Manage::where('son_id',$sid)->get()->toArray();
//            dump($id);
            foreach ($id as $value) {
                $d[] = $value['id'];
            }
            $list = $obj->whereIn('mid',$d)->Paginate(10)->toArray();
            //dd($list);
            if ($list == false && !empty($search)) {
                return redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            for ($i = 0; $i < count($list['data']); $i++) {
                if ($list['data'][$i]['status'] == 1) {
                    $list['data'][$i]['status'] = "1(已启用)";
                } else {
                    $list['data'][$i]['status'] = "0(已禁用)";
                }
                $list['data'][$i]['ip'] = long2ip($list['data'][$i]['ip']);
            }
            $list['searchtype'] = self::$field;
            $man = $obj->whereIn('mid',$d)->Paginate(10);
//            $man = $obj->where('mid',Session::get('id'))->Paginate(10);
//            $man = $obj->Paginate(10);
        }
        else {
            $list = $obj->where('mid',Session::get('id'))->Paginate(10)->toArray();
            //dd($list);
            if ($list == false && !empty($search)) {
                return redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            for ($i = 0; $i < count($list['data']); $i++) {
                if ($list['data'][$i]['status'] == 1) {
                    $list['data'][$i]['status'] = "1(已启用)";
                } else {
                    $list['data'][$i]['status'] = "0(已禁用)";
                }
                $list['data'][$i]['ip'] = long2ip($list['data'][$i]['ip']);
            }
            $list['searchtype'] = self::$field;
            $man = $obj->where('mid',Session::get('id'))->Paginate(10);
        }
        //dd($man);
        return view('admin.users.index',['list'=>$list,'man'=>$man,'search'=>$search,'param'=>$param]);
    }
//    //载入用户收藏列表页
//    public function collectionList($id)
//    {
//
//        $user = Users::where('id',$id)->select('username','id')->first()->toArray();
//        //$list = Users::find(1)->collection;dd($list);
//        $list = Collection::where('uid',$user['id'])->Paginate(5)->toArray();
//
//        for ($i=0;$i<count($list['data']);$i++){
//            $list['data'][$i]['username'] = $user['username'];
//            $pro = Product::where('id',$list['data'][$i]['pid'])->first();
//            if($pro)$pro->toArray();
//            $protype = Artist_category::where('id',$pro['artist_id'])->first();
//            if($protype)$protype->toArray();
//            $list['data'][$i]['artist'] = $protype['name'];
//            $list['data'][$i]['space'] = $pro['space'];
//            $list['data'][$i]['style'] = $pro['style'];
//            $list['data'][$i]['theme'] = $pro['theme'];
//            $list['data'][$i]['series'] = $pro['series'];
//            $list['data'][$i]['frame'] = $pro['frame'];
//            $list['data'][$i]['symbolic'] = $pro['symbolic'];
//            $list['data'][$i]['picture'] = $pro['picture'];
//            $list['data'][$i]['num_c'] = $pro['num_c'];
//            $list['data'][$i]['num_d'] = $pro['num_d'];
//        }
//        //dd($list);
//        if($list){
//            $data['searchtype'] = self::$fieldCollection;
//            //dd($list);
//            $page = Collection::where('uid',$user['id'])->Paginate(5);
//            return view('admin.users.collectionlist',['list'=>$list,'page'=>$page,'data'=>$data]);
//        }else{
//            return  redirect()->back()->withInput()->withErrors('载入失败');
//        }
//    }

    //载入积分管理
    public function integralList($id) {
        //dump($id);
        $re = Array();
        $list = Users::where('id',$id)->first()->toArray();
        $record = Record::where('user_id',$id)->orderBy('id','desc')->Paginate(10);
        return view('admin.users.integralList',['list'=>$list,'record' => $record]);
    }

    //管理积分
    public function integral() {
        $id = input::get('id');
        $add = input::get('add');
        $way = input::get('way');
        $session = Session::get('id');

        if($way !== null) {
            if($add != 0) {
                $list = Record::insert([
                    'user_id' => $id,
                    'manage_id' => $session,
                    'change_integral' => $add,
                    'change_way' => $way,
                ]);
                if ($list) {
                    $integral = Users::where('id', $id)->first()->toArray();
                    if ($way == 1) {
                        $data['integral'] = (int)$integral['integral'] + (int)$add;
                    }
                    if ($way == 2) {
                        $data['integral'] = (int)$integral['integral'] - (int)$add;
                    }
                    $text = Users::where('id', $id)->update($data);
                    if ($text) {
                        return Redirect::to('admin/users/integralList/' . $id)->withErrors('修改成功!');
                    } else {
                        return redirect()->back()->withInput()->withErrors('修改失败!');
                    }
                }
            }
            else {
                return redirect()->back()->withInput()->withErrors('未做修改!');
            }
        }
        else {
            return redirect()->back()->withInput()->withErrors('请选择修改方式!');
        }
    }


    //启用/禁用账号
    public function setStatus($id,$status)
    {
        $c = Users::where('id',$id)->where('status',$status)->get()->toArray();
        if($c){
            return  redirect()->back()->withInput()->withErrors('已经设置');
        }
        $map = Users::where('id',$id)->update(['status'=>$status]);
        if($map){
            return back()->withErrors('设置成功');
        }else{
            return back()->withErrors('设置失败');
        }
    }



    //批量导入客户信息
    public function impUser() {
        $s = array();
        $k = array();
        $input_error = null;
        $file = input::file('file');
        $radio = input::get('radio');
        if(empty($file)) {
            return redirect()->back()->withInput()->withErrors('请选择上传文件!');
        }

        if($file->isValid()) {
            $allowed_extensions = ["xls", "xlsx"];
            if($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(),$allowed_extensions)) {
                return ['error' => 'You may only upload xls or xlsx.'];
            }
            $destinationPath = 'exports';  //public文件夹下新建storage/uploads文件夹
            $extension = $file->getClientOriginalExtension();
            $fileName = str_random(10) . '.' . $extension;
            $file->move($destinationPath,$fileName);
            $filePath = asset($destinationPath.'/'.$fileName);
        }
        DB::beginTransaction();

        try {
            $fileExcel = "exports/".iconv('UTF-8', 'GBK', $fileName);
            //excel文件导入闭包开始
            $result = Excel::load($fileExcel, function($reader) use($radio) {
                $data = $reader->all()->toArray();
                //dd($data);
                $o = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
                foreach ($data as $da => $value) {
                    if($radio ==1 ) {  //跳过重复
                        $map = Users::where('car_num',$value['car_num'])->first();
                        if(empty($map)) {
                            $list = Users::insert([
                                'username'=>$value['username'],
                                'password'=>md5(123456),
                                'integral'=>$value['integral'],
                                'phone'=>$value['phone'],
                                'email'=>$value['email'],
                                'sex'=>$value['sex'],
                                'birth'=>$value['birth'],
                                'car_num'=>$value['car_num'],
                                'user_num'=>$value['user_num'],
                                'name'=>$value['name'],
                                'mid'=>Session::get('id'),
                                'u_batch' => $o,
                                'address' => $value['address'],
                                'status'=>1,
                            ]);
//                            $aid = Users::where('car_num',$value['car_num'])->first();
//                            $address = Address::insert([
//                                'user_id' => $aid['id'],
//                                'get_name' => $value['name'],
//                                'get_address' => $value['address'],
//                                'get_phone' => $value['phone'],
//                            ]);
                        }
                    }
                    if($radio == 2) {  //覆盖重复
                        $map = Users::where('car_num',$value['car_num'])->first();
                        if(empty($map)) {
                            $list = Users::insert([
                                'username'=>$value['username'],
                                'password'=>md5(123456),
                                'integral'=>$value['integral'],
                                'phone'=>$value['phone'],
                                'email'=>$value['email'],
                                'sex'=>$value['sex'],
                                'birth'=>$value['birth'],
                                'car_num'=>$value['car_num'],
                                'user_num'=>$value['user_num'],
//                                'address'=>$value['address'],
                                'name'=>$value['name'],
                                'mid'=>Session::get('id'),
                                'u_batch' => $o,
                                'address' => $value['address'],
                                'status'=>1,
                            ]);
//                            $aid = Users::where('car_num',$value['car_num'])->first();
//                            $address = Address::insert([
//                                'user_id' => $aid['id'],
//                                'get_name' => $value['name'],
//                                'get_address' => $value['address'],
//                                'get_phone' => $value['phone'],
//                            ]);
                        }
                        else {
                            $list = Users::where('id',$map['id'])->update([
                                'username'=>$value['username'],
                                'password'=>md5(123456),
                                'integral'=>$value['integral'],
                                'phone'=>$value['phone'],
                                'email'=>$value['email'],
                                'sex'=>$value['sex'],
                                'birth'=>$value['birth'],
                                'car_num'=>$value['car_num'],
                                'user_num'=>$value['user_num'],
//                                'address'=>$value['address'],
                                'name'=>$value['name'],
                                'mid'=>Session::get('id'),
                                'u_batch' => $o,
                                'address' => $value['address'],
                                'status'=>1,
                            ]);
//                            $address = Address::where('user_id',$map['id'])->update([
//                                'get_name' => $value['name'],
//                                'get_address' => $value['address'],
//                                'get_phone' => $value['phone'],
//                            ]);
                        }
                    }
                }
            });
 //       dd($data);
            DB::commit();
        }
        catch (\Exception $e) {
            return back()->withErrors('导入文件有误!');
            DB::rollBack();
        }
        return Redirect::to('admin/users')->withErrors('客户导入成功!');
    }

    //载入添加页面
    public function add() {
        return view('admin.users.userAdd');
    }

    //添加会员
    public function addUser() {
        $dd = Users::select('id','name')->get()->toArray();
        $mid = Session::get('id');
        $name = input::get('name');
        $sex = input::get('sex');
        $car_num = input::get('car_num');
        $integral = input::get('integral');
        $email = input::get('email');
        $phone = input::get('phone');
        $address = input::get('address');
        if(empty($mid) || empty($name) || empty($car_num) || empty($phone)) {
            return back()->withErrors('缺少参数!');
        }
        $map = Users::where('car_num',$car_num)->first();
        if(empty($map)) {
            $list = Users::insert([
                'name' => $name,
                'password'=>md5(123456),
                'sex' => $sex,
                'integral' => $integral,
                'email' => $email,
                'phone' => $phone,
                'car_num' => $car_num,
                'mid' => $mid,
                'address' => $address,
                'status' =>1,
            ]);
            if($list) {
                return Redirect::to('admin/users')->withErrors('客户添加成功!');
            }
            else {
                return back()->withErrors('导入失败!');
            }
        }
        else {
            return back()->withErrors('该客户已存在!');
        }
    }

    //获取会员信息
    public function getUser($id) {
        $list = Users::where('id',$id)->first()->toArray();
        $manage = Manage::all()->toArray();
        return view('admin.users.updateUser',['value'=>$list,'man'=>$manage]);
    }

    //更新会员信息
    public function updateUser() {
        $uid = input::get('uid');
//        dump($uid);
        $mid = input::get('mid');
//        dump($mid);
        $name = input::get('name');
        $sex = input::get('sex');
        $car_num = input::get('car_num');
        $integral = input::get('integral');
        $email = input::get('email');
        $phone = input::get('phone');
        $address = input::get('address');
//        if(empty($mid) || empty($name) || empty($car_num) || empty($phone)) {
//            return back()->withErrors('缺少参数!');
//        }
//        dump($name);
        $data['name'] = $name;
        $data['sex'] = $sex;
        $data['car_num'] = $car_num;
        $data['integral'] = $integral;
        $data['email'] = $email;
        $data['phone'] = $phone;
        $data['mid'] = $mid;
        $data['address'] = $address;
//        dd($data);
        $update = Users::where('id',$uid)->update($data);
        if($update) {
            return Redirect::to('admin/users')->withErrors('更新成功!');
        }
        else {
            return back()->withErrors('更新失败!');
        }
    }

    //导出名单
    public function export($batch,$search) {
        $obj = new Users;
        if ($search == 1) {
            $obj = $obj->where('id', 'like', "%$batch%");
            //dd($obj);
        } elseif ($search == 2) {
            $obj = $obj->where('create_time', 'like', "%$batch%");
        } elseif ($search == 3) {
            $obj = $obj->where('update_time', 'like', "%$batch%");
        } elseif ($search == 4) {
            $obj = $obj->where('rank', 'like', "%$batch%");
        } elseif ($search == 5) {
            $obj = $obj->where('name', 'like', "%$batch%");
        } elseif ($search == 6) {
            $obj = $obj->where('integral', 'like', "%$batch%");
        } elseif ($search == 7) {
            $obj = $obj->where('phone', 'like', "%$batch%");
        } elseif ($search == 8) {
            $obj = $obj->where('email', 'like', "%$batch%");
        } elseif ($search == 9) {
            $obj = $obj->where('sex', 'like', "%$batch%");
        } elseif ($search == 10) {
            $obj = $obj->where('birth', 'like', "%$batch%");
        } elseif ($search == 11) {
            $obj = $obj->where('car_num', 'like', "%$batch%");
        } elseif ($search == 12) {
            $obj = $obj->where('user_num', 'like', "%$batch%");
        } elseif ($search == 13) {
            $man = Manage::where('username','like',"%$batch%")->first();
            $obj = $obj->where('mid',$man['id']);
        } elseif ($search == 14) {
            $obj = $obj->where('u_batch', 'like', "%$batch%");
        } elseif ($search == 15) {
            $obj = $obj->where('status', 'like', "%$batch%");
        }
        $list = $obj->get();
//        dd($obj)->toArray();
//        dd($list);
        $l = [
            ['name','phone','car_num','address','integral','manage_id','goods','number','price','sericve']
        ];
        foreach ($list as $value) {
            $t[0] = $value['name'];
            $t[1] = $value['phone'];
            $t[2] = $value['car_num'];
            $t[3] = $value['address'];
            $t[4] = $value['integral'];
            $t[5] = $value['mid'];
            $l[] = $t;
        }
        Excel::create('客户信息',function($excel) use ($l) {
            $excel->sheet('score',function ($sheet) use ($l) {
                $sheet->rows($l);
            });
        })->export('xls');
    }

    //批量导出
    public function exports($batch) {
        $list = Users::where('u_batch',$batch)->get();
        $l = [
            ['name','phone','car_num','address','integral','manage_id','goods','number','price','sericve']
        ];
        foreach ($list as $value) {
            $t[0] = $value['name'];
            $t[1] = $value['phone'];
            $t[2] = $value['car_num'];
            $t[3] = $value['address'];
            $t[4] = $value['integral'];
            $t[5] = $value['mid'];
            $l[] = $t;
        }
        Excel::create('message',function($excel) use ($l) {
            $excel->sheet('score',function ($sheet) use ($l) {
                $sheet->rows($l);
            });
        })->export('xls');
    }
//    //载入添加客户经理页面
//    public function director() {
//        return view('admin.users.director');
//    }
//
//    //添加信息
//    public function addDire() {
//        $username = Input::get('name');
//        $password = Input::get('password');
//        $email = input::get('email');
//        $phone = input::get('phone');
//        $role = Session::get('roleid');
//        if (!empty($role) && $role != 1){
//            return  redirect()->back()->withInput()->withErrors('没有权限！');
//        }
//        $list = Users::insert(['username'=>$username , 'password'=>md5($password) ,'login_time'=>date("Y-m-d H:i:s"), 'rank'=>2,'email'=>$email,'phone'=>$phone]);
//        if($list){
//            return Redirect::to("admin/director")->withErrors('添加成功！');
//        }else{
//            return  back()->withErrors('添加失败！');
//        }
//    }
//
//    //客户经理列表
//    public function dlist() {
//        $list = Users::where('rank','!=',0)->get()->toArray();
//        return view('admin.users.dlist',['list'=>$list]);
//    }

    public function addUsers() {
        $res = array();
        $user_name = Input::get('user_name');
        $car_num = Input::get('car_num');
        $integ = Input::get('integ');
        $phone = Input::get('phone');
        $address = Input::get('address');
        $batch = Input::get('batch');
        $user = Users::where('car_num',$car_num)->first();
//        dump($user);
        if($user) {
            return [
                'error' => 3,
                'msg' => '用户已存在!'
            ];
        }
        if(Session::get('roleid') != 3) {
            $list = Users::insert([
                'name' => $user_name,
                'password' => md5(123456),
                'car_num' => $car_num,
                'integral' => $integ,
                'phone' => $phone,
                'mid' => Session::get('id'),
                'u_batch' => $batch,
            ]);
            $map = Users::where('name',$user_name)->where('car_num',$car_num)->first();
            $add = Address::insert([
                'user_id' => $map['id'],
                'get_name' => $user_name,
                'get_address' => $address,
                'get_phone' => $phone,
            ]);
            if($list && $add) {
                return [
                    'error' => 0,
                    'msg' => '添加成功!',
                ];
            }
            else {
                return [
                    'error' => 1,
                    'msg' => '添加失败!'
                ];
            }
        }
        else {
            return [
                'error' => 2,
                'msg' => '没有权限!'
            ];
        }
    }

    //批量显示
    public function auditUsers() {
        $v = array();
        $t = array();
        $y = array();
        $roleid = Session::get('roleid');
        if($roleid == 1) {
            $batch = Users::whereNotNull('u_batch')->orderBy('create_time','desc')->get()->toArray();
//            dump($batch);
        }
        elseif($roleid == 2 or $roleid == 3) {
            if($roleid == 3) {
                $pid = Manage::where('id',Session::get('id'))->first();
                $sid = Manage::where('son_id',$pid['son_id'])->get();
            }
            else {
                $sid = Manage::where('son_id',Session::get('id'))->get();
            }
            foreach($sid as $s) {
                $y[] = $s['id'];
            }
            $batch = Users::whereIn('mid',$y)->whereNotNull('u_batch')->orderBy('create_time','desc')->get();
        }
        else{
            $batch = Users::where('mid',Session::get('id'))->whereNotNull('u_batch')->orderBy('create_time','desc')->get();
        }
        foreach ($batch as $l=>$value) {
            $isin = in_array($value['u_batch'],$v);
            if(!$isin) {
                $v[] = $value['u_batch'];
                $t[] = $value;
            }
        }
//        dd($t);
        return view('admin.users.audit',['v'=>$t]);
    }

    //详细显示
    public function toAudit($batch) {
        $list = Users::where('u_batch',$batch)->orderBy('create_time','desc')->get()->toArray();
        return view('admin.users.toAudit',['list'=>$list,'batch'=>$batch]);
    }

    //删除批次会员
    public function delete($batch) {
        $del = Users::where('u_batch',$batch)->delete();
        if($del) {
            return back()->withErrors('删除成功!');
        }
        else {
            return back()->withErrors('删除失败!');
        }
    }
}